package com.siao.utils
{
	import flash.utils.ByteArray;
	
	/**
	 * 字节数组转义工具
	 * @author SiaoLeon
	 */
	public class Bytes
	{
		/**
		 * 根据字符串定义的字节转换为字节数组
		 * @param source 字符串
		 * @param radix 进制(默认16进制)
		 */
		public static function decode(source:String, radix:uint=16):ByteArray
		{
			var result:ByteArray = new ByteArray();
			
			var bytes:Array = source.toUpperCase().split(/[^a-fA-F0-9]+/);
			
			for each (var char:String in bytes)
			{
				var byte:int = int(parseInt(char, radix));
				result.writeByte(byte);
			}
			
			result.position = 0;
			
			return result;
		}
		
		/**
		 * 根据字节数组转换为字符串形式
		 * @param source 字节流
		 * @param offset 起始位置
		 */
		public static function encode(source:ByteArray, offset:int=0):String
		{
			var result:String = "";
			
			if (source == null)
			{
				return result;
			}
			
			var position:uint = source.position;
			
			source.position = offset;
			
			while (source.bytesAvailable > 0)
			{
				var byte:uint = uint(source.readByte());
				
				if (result != "")
				{
					result += " ";
				}
				
				var hex:String = byte.toString(16).toUpperCase();
				hex = "00" + hex;
				hex = hex.substr(hex.length - 2);
				
				result += hex;
			}
			
			source.position = position;
			
			return result;
		}
	
	}
}
